package com.zhiyou.app.shop.website.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.zhiyou.app.shop.common.BaseAction;
import com.zhiyou.app.shop.common.util.ShopConstants;
import com.zhiyou.app.shop.website.dao.impl.UserInfoDaoImpl;
import com.zhiyou.app.shop.website.dao.pojo.DicItem;
import com.zhiyou.app.shop.website.dao.pojo.EpComplain;
import com.zhiyou.app.shop.website.dao.pojo.EpList;
import com.zhiyou.app.shop.website.dao.pojo.User;
import com.zhiyou.app.shop.website.dao.pojo.UserAccount;
import com.zhiyou.app.shop.website.dao.pojo.UserBank;
import com.zhiyou.app.shop.website.service.IDicItemService;
import com.zhiyou.app.shop.website.service.IEpComplainService;
import com.zhiyou.app.shop.website.service.IEpListService;
import com.zhiyou.app.shop.website.service.IUserAccountService;
import com.zhiyou.app.shop.website.service.IUserManagerService;

public class EpManagerAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	
	@Autowired
	private IUserManagerService userManagerService;
	@Autowired
	private IUserAccountService userAccountService;
	@Autowired
	private IDicItemService dicItemService;
	@Autowired
	private IEpListService epListService;
	@Autowired
	private IEpComplainService epComplainService;
 
	private UserBank userBank;
	private UserAccount userAccount;
	private String epfee;
	private String eppayfee;
	private String prizeAmount;
	private List<Map> epList = new ArrayList<Map>();
	private String id;  //ep id
	private EpList ep; 
	private User saleUser;
	private List<DicItem> epStatusList;
	private EpComplain epComplain;
	
	public String epPage(){
		pageSize = 10;
		int pageOffset = new Integer(pageNo) != null ? (pageNo-1) * pageSize : 0;
		epList = epListService.findOnSale("1", getCurrentUser().getUserAccount(), pageOffset, pageSize);
		pageNo = pageOffset/pageSize + 1;
		//epStatusList = dicItemService.findByType(ShopConstants.EP_STATUS);
		int totalCount = epListService.findOnSaleCnt("1", getCurrentUser().getUserAccount());
		totalPage = totalCount%pageSize!=0?totalCount/pageSize+1:totalCount/pageSize;
		return SUCCESS;
	}
	
	/**
	 * 卖出页面
	 * @return
	 */
	public String epSalePage(){
		List<UserBank> list = userManagerService.getUserBankByUid(getCurrentUser().getUserAccount());
		if(list != null && list.size() >0){
			userBank = list.get(0);
		}
		userAccount = userAccountService.findUserAccount(getCurrentUser().getUserAccount());
		List<DicItem> listep = dicItemService.findByType(ShopConstants.EP_FEE);  //手续费 3%
		if(listep != null && listep.size() >0 ){
			epfee = listep.get(0).getCode();
		}
		List<DicItem> listeppay = dicItemService.findByType(ShopConstants.EP_CARRY_FEE);  //手续费 3%
		if(listeppay != null && listeppay.size() >0 ){
			eppayfee = listeppay.get(0).getCode();
		}
		return SUCCESS;
	}
	/**
	 * 卖出奖金币
	 * @return
	 */
	public String epSale(){
		getResponse().setContentType("text/html; charset=UTF-8");
		PrintWriter out;
		try {
			userAccount = userAccountService.findUserAccount(getCurrentUser().getUserAccount());
			List<DicItem> listep = dicItemService.findByType(ShopConstants.EP_FEE);  //手续费 3%
			if(listep != null && listep.size() >0 ){
				epfee = listep.get(0).getCode();
			}
			List<DicItem> listeppay = dicItemService.findByType(ShopConstants.EP_CARRY_FEE);  //汇款费 1%
			if(listeppay != null && listeppay.size() >0 ){
				eppayfee = listeppay.get(0).getCode();
			}
			//手续费
			BigDecimal charge = new BigDecimal(prizeAmount).multiply(new BigDecimal(epfee));
			//汇款费
			BigDecimal post = new BigDecimal(prizeAmount).multiply(new BigDecimal(eppayfee));
			
			EpList ep = new EpList();
			ep.setUserId(getCurrentUser().getUserAccount());
			ep.setDealAmount(new BigDecimal(prizeAmount));
			ep.setNeedAmont(new BigDecimal(prizeAmount).add(charge));
			ep.setType("");
			ep.setStatus("1"); //卖出状态
			ep.setCreateDate(new Timestamp(new Date().getTime()));
			ep.setChargeFee(charge);
			ep.setPostFee(post);
			epListService.saveEpTrade(getCurrentUser().getUserAccount(), ep);
			
			getResponse().setContentType("text/html; charset=UTF-8");
			out = getResponse().getWriter();
			out.print("EP交易信息已挂出,为出售状态");
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String confirmPage(){
		try {
			User user = getCurrentUser();
			ep = epListService.findbyId(id);
			//ep.setRelationId(user.getUserAccount());
			user.setCreditLevel((new Integer(user.getCreditLevel())-1)+"");
			//epListService.saveEp(user,ep,"0"); //不给卖方发汇款通知
			userManagerService.saveUser(user);
			List<User> listu = userManagerService.getUser(ep.getUserId());
			if(listu != null && listu.size() > 0){
				saleUser = listu.get(0);			
			}
			List<UserBank> list = userManagerService.getUserBankByUid(ep.getUserId());
			if(list != null && list.size() >0){
				userBank = list.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public String confirm(){
		User user = getCurrentUser();
		ep = epListService.findbyId(id);
		ep.setStatus("2");  //交易中
		ep.setType("1");// 1:未汇款
		ep.setRelationId(user.getUserAccount());
		user.setCreditLevel((new Integer(user.getCreditLevel())+1)+"");
		try {
			getResponse().setContentType("text/html; charset=UTF-8");
			epListService.saveEp(user,ep,"1"); //并给卖方发汇款通知
			PrintWriter out = getResponse().getWriter();
			out.print("EP交易成功，请尽快交易汇款");
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private Integer totalPage;
	public String epmore(){
		pageSize = 20;
		int pageOffset = new Integer(pageNo) != null ? (pageNo-1) * pageSize : 0;
		epList = epListService.findepbyuser(getCurrentUser().getUserAccount(), pageOffset, pageSize);
		pageNo = pageOffset/pageSize + 1;
		epStatusList = dicItemService.findByType(ShopConstants.EP_STATUS);
		int totalCount = epListService.findepCntbyuser(getCurrentUser().getUserAccount());
		totalPage = totalCount%pageSize!=0?totalCount/pageSize+1:totalCount/pageSize;
		return SUCCESS;
	}
	//交易成功   将对应奖金币划入买方账户
	public String confirmRemit(){
		ep = epListService.findbyId(id);
		epListService.epTradeSuc(ep); //交易成功
		getResponse().setContentType("text/html; charset=UTF-8");
		PrintWriter out;
		try {
			out = getResponse().getWriter();
			out.print("汇款成功，确认收款");
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	//买方已经汇款      提醒卖方 确认收款
	public String onRemit(){
		//id = getRequest().getParameter("id");
		ep = epListService.findbyId(id);
		ep.setType("2");  //已汇款
		epListService.epRemit(ep); //等待卖方确认收款
		getResponse().setContentType("text/html; charset=UTF-8");
		PrintWriter out;
		try {
			out = getResponse().getWriter();
			out.print("汇款成功，等待卖方确认收款");
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//EP交易挂出后，没有交易之前可以取消
	public String epCancel(){
		epListService.epCancel(id);
		getResponse().setContentType("text/html; charset=UTF-8");
		try {
			PrintWriter out = getResponse().getWriter();
			out.print("EP交易已取消");
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 买入页面
	 * @return
	 */
	public String epBuyPage(){
		
		return SUCCESS;
	}

	//EP交易协议
	public String protocols(){
		
		return SUCCESS;
	}
	
	private String account;
	public String epBank(){
		ep = epListService.findbyId(id);
		userBank = userManagerService.findByAccount(account);
		return SUCCESS;
	}
	
	//投诉
	public String complainPage(){
		ep = epListService.findbyId(id);
		epComplain = epComplainService.findByEpId(id);
		if(epComplain == null)
			epComplain = new EpComplain();
		return SUCCESS;
	}
	
	private File file;  //上传的文件
	private String fileFileName;  //文件名称
	private String fileContentType;   //文件类型
	public String doComplain() throws Exception{
		getResponse().setContentType("text/html; charset=UTF-8");
		User user = getCurrentUser();
		//String realPath = ServletActionContext.getServletContext().getRealPath("images");
		String uplodDir = ShopConstants.UPLOAD_PATH;
		System.out.println("real Path:"+uplodDir);
		if(file != null){
			String newFileName = System.currentTimeMillis() + (new Random()).nextInt() + "."+ FilenameUtils.getExtension(fileFileName);
			File savefile = new File(new File(uplodDir), newFileName);
			if(!savefile.getParentFile().exists()){
				savefile.getParentFile().mkdirs();
			}
			FileUtils.copyFile(file, savefile);
			epComplain.setAttName(fileFileName);
			String filepath = savefile.getAbsolutePath();
			if (filepath.contains("\\")) {// 支持windows操作系统
				filepath = filepath.replaceAll("\\\\", "/");
			}
			epComplain.setAttPath(filepath);
		}
		ep = epListService.findbyId(epComplain.getEpId());
		ep.setComplainStatus("1");  //已投诉 未处理     2：已处理
		epListService.update(ep);
		epComplain.setUserId(user.getUserAccount());
		epComplain.setCreateDate(new Timestamp(System.currentTimeMillis()));
		epComplain.setHandle("1");
		epComplainService.save(epComplain);
		PrintWriter out = getResponse().getWriter();
		out.print("投诉已提交，等待客服处理");
		out.flush();
		out.close();
		return null;
	}
	
	public String deleteAtt(){
		getResponse().setContentType("text/html; charset=UTF-8");
		epComplain = epComplainService.findById(new Integer(id));
		epComplain.setAttName("");
		epComplain.setAttPath("");
		epComplainService.save(epComplain);
		PrintWriter out;
		try {
			out = getResponse().getWriter();
			out.print("附件凭证已删除，请重新添加附件凭证");
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public UserBank getUserBank() {
		return userBank;
	}

	public void setUserBank(UserBank userBank) {
		this.userBank = userBank;
	}

	public UserAccount getUserAccount() {
		return userAccount;
	}

	public void setUserAccount(UserAccount userAccount) {
		this.userAccount = userAccount;
	}

	public String getEpfee() {
		return epfee;
	}

	public void setEpfee(String epfee) {
		this.epfee = epfee;
	}

	public String getEppayfee() {
		return eppayfee;
	}

	public void setEppayfee(String eppayfee) {
		this.eppayfee = eppayfee;
	}

	public String getPrizeAmount() {
		return prizeAmount;
	}

	public void setPrizeAmount(String prizeAmount) {
		this.prizeAmount = prizeAmount;
	}

	public List<Map> getEpList() {
		return epList;
	}

	public void setEpList(List<Map> epList) {
		this.epList = epList;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public EpList getEp() {
		return ep;
	}

	public void setEp(EpList ep) {
		this.ep = ep;
	}

	public User getSaleUser() {
		return saleUser;
	}

	public void setSaleUser(User saleUser) {
		this.saleUser = saleUser;
	}

	public List<DicItem> getEpStatusList() {
		return epStatusList;
	}

	public void setEpStatusList(List<DicItem> epStatusList) {
		this.epStatusList = epStatusList;
	}

	public Integer getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(Integer totalPage) {
		this.totalPage = totalPage;
	}

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public EpComplain getEpComplain() {
		return epComplain;
	}

	public void setEpComplain(EpComplain epComplain) {
		this.epComplain = epComplain;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

}
